<?php

Yii::import('application.extensions.Api._base.BaseApiFunctionality');

class authApiFunctionality extends BaseApiFunctionality {
    /* --------------- Start  GET Actions --------------------- */


    /* --------------- End GET Actions ------------------------ */


    /* --------------- Start POST Actions --------------------- */

    function login() {
        if ($this->validPostRequest()) {
            $data='';
            if (empty($_POST['user_name']) && empty($_POST['password'])) {
                $data = new ECOMResult(501, 'Please enter a username and password.');
                ECOMApiResponder::Respond($data, date('m-d-Y'));
            }

            if (empty($_POST['user_name'])) {
                $data = new ECOMResult(501, 'Please enter a username.');
                ECOMApiResponder::Respond($data, date('m-d-Y'));
            }

            if (empty($_POST['password'])) {
                $data = new ECOMResult(501, 'Please enter a password.');
                ECOMApiResponder::Respond($data, date('m-d-Y'));
            }


            $username = $_POST['user_name'];
            $password = $_POST['password'];

// Find the user
            // $user = Users::model()->find('LOWER(username)=?', array(strtolower($username)));
            $user = Users::model()->with(array(
                        'userHasRoles' => array(
                            // we don't want to select userhasroles field
                            'select' => false,
                            // but want to get only users with role id 2
                            'joinType' => 'INNER JOIN',
                            'condition' => 'userHasRoles.roles_id=' . Roles::APPUSER,
                        ),
                    ))->find('LOWER(username)=?', array(strtolower($username)));

            if ($user === null) {
// Error: Unauthorized
                if (empty($data)) {
                    $data = new ECOMResult(501, 'User not found. Please check the username and try again.');
                }
                ECOMApiResponder::Respond($data, date('m-d-Y'));
            } else if (!$user->validatePassword($password)) {
// Error: Unauthorized
                $data = new ECOMResult(501, 'Incorrect Password. Please check the password you provided and try again.');
                ECOMApiResponder::Respond($data, date('m-d-Y'));
            }else{
              $user_id = $user->getAttribute('id');

            if ($user_id) {
                $data = self::getAuthKey($user_id);
            } else {
                $data = new ECOMResult(501, 'Unable to authenticate user. Please check the username and password and try again.');
            }  
            }

            

            ECOMApiResponder::Respond($data, date('m-d-Y'));
        }
    }

   
    protected static function getAuthKey($user_id) {
        $auth = new AuthKey();
        if ($auth->InsertAuthKey($user_id)) {
            $data = array('auth_key' => $auth->getAttribute('auth_key'));
        } else {
            $data = array('auth_key' => NULL);
        }
        return $data;
    }

    function forgotPassword() {
        if ($this->validPostRequest()) {
            $userName = $_POST['username'];
            if (empty($userName)) {
                $data = new ECOMResult(501, 'Please enter username');
            } else {
                $user = Users::model()->find('username=:username', array(':username' => $userName));
                if (!$user) {
                    $data = new ECOMResult(501, 'Please enter correct username');
                } else {
                    $profiles = Profiles::model()->find('user_id=:user_id', array(':user_id' => $user->id));
                    if (is_array($profiles)) {

                        $email = $profiles[0]->getAttribute('email');
                    } else {
                        $email = $profiles->getAttribute('email');
                    }

                    if ($email) {
                        $key = guid();
                        $user->activationKey = $key;
                        try {

                            $user->save(false);
                            $msgTpl = 'forgatePasswordTemplate.php';
                            $subject = 'Your Password Link';
                            $activation_url = 'http://' . $_SERVER['HTTP_HOST'] . Yii::app()->createUrl('user/user/recovery', array("activationKey" => $user->activationKey, "username" => $user->username));
                            forgatePasswordEmail($email, $user, $activation_url, $subject, $msgTpl);
                            $data = new ECOMResult(200, ' Email send successfully.');
                        } catch (Exception $exc) {
                            $data = new ECOMResult(501, 'Sorry! There is some problem. Please try again later.');
                        }
                    } else {
                        $data = new ECOMResult(501, 'Email id is not given');
                    }
                }
            }
            ECOMApiResponder::Respond($data, date('m-d-Y'));
        }
    }

    /* --------------- End POST Actions --------------------- */
}

?>
